﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using TransControlSystem.Dao;
using TransControlSystem.Model;
using TransControlSystem.Utils;
using TransControlSystem.ViewModel.Common;
using TransControlSystem.ViewModel.Common.Command;

namespace TransControlSystem.ViewModel
{
    /// <summary>
    /// 标签信息配置后台逻辑
    /// </summary>
    #region 枚举
    public enum IsEnable { 已禁用, 已启用 }
    #endregion 枚举
    public class TagInfoConfigViewModel : ViewModelBase
    {

        #region 搜索条件
        //所属设备
        public string EquipmentName { set; get; }
        //含义
        public string TagDesc { set; get; }
        //地址
        public string Address { set; get; }
        //数据类型
        public string ValueType { set; get; }
        //读写属性
        public string ReadOrWriteText { set; get; }
        //是否可用
        public string IsEnableText { set; get; }
        #endregion 搜索条件

        //标签队列
        private ObservableCollection<TagInfo> _TagInfoList;
        //标签队列
        public ObservableCollection<TagInfo> TagInfoList
        {
            get { return _TagInfoList; }
            set
            {
                _TagInfoList = value;
                RaisePropertyChanged("TagInfoList");
            }
        }
        //所属设备下拉菜单列表
        private ObservableCollection<string> _EquipmentNameItems = new ObservableCollection<string>();
        /// <summary>
        /// 所属设备下拉菜单列表
        /// </summary>
        public ObservableCollection<string> EquipmentNameItems
        {
            get { return _EquipmentNameItems; }
            set
            {
                _EquipmentNameItems = value;
                RaisePropertyChanged("EquipmentNameItems");
            }
        }
        //数据类型下拉菜单列表
        private ObservableCollection<string> _ValueTypeItems = new ObservableCollection<string>();
        /// <summary>
        /// 数据类型下拉菜单列表
        /// </summary>
        public ObservableCollection<string> ValueTypeItems
        {
            get { return _ValueTypeItems; }
            set
            {
                _ValueTypeItems = value;
                RaisePropertyChanged("ValueTypeItems");
            }
        }
        //读写属性下拉菜单列表
        private ObservableCollection<string> _ReadOrWriteItems = new ObservableCollection<string>();
        /// <summary>
        /// 读写属性下拉菜单列表
        /// </summary>
        public ObservableCollection<string> ReadOrWriteItems
        {
            get { return _ReadOrWriteItems; }
            set
            {
                _ReadOrWriteItems = value;
                RaisePropertyChanged("ReadOrWriteItems");
            }
        }

        //是否可用下拉菜单列表
        private ObservableCollection<string> _IsEnableItems = new ObservableCollection<string>();
        /// <summary>
        /// 是否可用下拉菜单列表
        /// </summary>
        public ObservableCollection<string> IsEnableItems
        {
            get { return _IsEnableItems; }
            set
            {
                _IsEnableItems = value;
                RaisePropertyChanged("IsEnableItems");
            }
        }
        //表格中的是否可用下拉菜单列表
        private ObservableCollection<string> _IsEnableItemsForDataGrid = new ObservableCollection<string>();
        /// <summary>
        /// 表格中的是否可用下拉菜单列表
        /// </summary>
        public ObservableCollection<string> IsEnableItemsForDataGrid
        {
            get { return _IsEnableItemsForDataGrid; }
            set
            {
                _IsEnableItemsForDataGrid = value;
                RaisePropertyChanged("IsEnableItemsForDataGrid");
            }
        }

        ///// <summary>
        ///// 编辑命令
        ///// </summary>
        //public DelegateCommand EditTagInfoCommand { get; set; }
        /// <summary>
        /// 搜索命令 
        /// </summary>
        public DelegateCommand SearchCommand { get; set; }
        /// <summary>
        /// 是否可用下拉菜单改变事件命令
        /// </summary>
        public DelegateCommand IsEnableSelectionChangedCommand { get; set; }
        /// <summary>
        /// 关闭窗体标识
        /// </summary>
        private bool toClose = false;
        /// <summary>
        /// 是否要关闭窗口
        /// </summary>
        public bool ToClose
        {
            get
            {
                return toClose;
            }
            set
            {
                toClose = value;
                if (toClose)
                {
                    RaisePropertyChanged("ToClose");
                }
            }
        }

        /// <summary>
        /// 构造方法
        /// </summary>
        public TagInfoConfigViewModel()
        {
            ////使用委托初始化编辑标签命令
            //EditTagInfoCommand = new DelegateCommand()
            //{
            //    ExecuteActionObj = new Action<object>(EditTagInfoHandler)
            //};
            //使用委托初始化搜索命令
            SearchCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SearchHandler)
            };
            //使用委托初始化是否启用下拉菜单改变事件
            IsEnableSelectionChangedCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(IsEnableSelectionChangedHandler)
            };
            //初始化搜索控件数据
            InitSearchControlData();
            //初始化标签列表
            InitTagInfoList();
            //注册刷新标签列表消息
            Messenger.Default.Register<NotificationMessage>(this, (nm) =>
            {
                if (nm.Notification == "TagInfoConfigReLoadTagList")
                {
                    InitTagInfoList();
                }
            });
        }

        /// <summary>
        /// 初始化搜索控件数据
        /// </summary>
        private void InitSearchControlData()
        {
            Application.Current.Dispatcher.Invoke((Action)delegate ()
            {
                //初始化搜索条件——设备下拉菜单
                EquipmentNameItems = new ObservableCollection<string>();
                EquipmentNameItems.Add("--请选择--");
                EquipmentNameItems.Add("堆垛机");
                EquipmentNameItems.Add("炉组");
                EquipmentNameItems.Add("解垛机");
                EquipmentNameItems.Add("加料车");
                //初始化搜索条件——数据类型下拉菜单
                ValueTypeItems = new ObservableCollection<string>();
                ValueTypeItems.Add("--请选择--");
                ValueTypeItems.Add("Bool");
                ValueTypeItems.Add("DInt");
                //初始化搜索条件——读写属性下拉菜单
                ReadOrWriteItems = new ObservableCollection<string>();
                ReadOrWriteItems.Add("--请选择--");
                ReadOrWriteItems.Add("可读");
                ReadOrWriteItems.Add("可读可写");
                //初始化搜索条件——是否可用下拉菜单
                IsEnableItems = new ObservableCollection<string>();
                IsEnableItems.Add("--请选择--");
                IsEnableItems.Add("已启用");
                IsEnableItems.Add("已禁用");
                //初始化表格中——是否可用下拉菜单
                IsEnableItemsForDataGrid = new ObservableCollection<string>();
                IsEnableItemsForDataGrid.Add("已启用");
                IsEnableItemsForDataGrid.Add("已禁用");
            });
        }

        ///// <summary>
        ///// 编辑标签信息处理程序
        ////</summary>
        ///// <param name="obj">参数：被编辑的标签</param>
        //private void EditTagInfoHandler(object obj)
        //{
        //    TagInfo TagInfo = (TagInfo)obj;
        //    //WindowManager.ShowEditTagInfo("EditValueWindow", TagInfo);
        //}

        /// <summary>
        /// 搜索命令处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void SearchHandler(object obj)
        {
            InitTagInfoList();
        }

        /// <summary>
        /// 是否启用下拉菜单改变事件处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void IsEnableSelectionChangedHandler(object obj)
        {
            SaveTagInfo((TagInfo)obj);
        }
        /// <summary>
        /// 保存标签信息
        /// </summary>
        /// <param name="tagInfo"></param>
        private void SaveTagInfo(TagInfo tagInfo)
        {
            try
            {
                if (tagInfo.Remark != null && tagInfo.Remark.Trim() != "" && XyhUtils.IsHasSQLInject(tagInfo.Remark))
                {
                    WindowManager.ShowWarning("警告", "说明不可使用包含SQL注入关键词的内容进行保存操作！");
                    return;
                }
                else if (tagInfo.Address != null && tagInfo.Address.Trim() != "" && XyhUtils.IsHasSQLInject(tagInfo.Address))
                {
                    WindowManager.ShowWarning("警告", "地址不可使用包含SQL注入关键词的内容进行保存操作！");
                    return;
                }
                //数据库中的标签
                TagInfo Befre = DapperTools.Query<TagInfo>("select * from TagInfo where Id = @Id", tagInfo);
                //要求改的标签
                TagInfo UpdataData = new TagInfo
                {
                    Id = tagInfo.Id,
                    Remark = tagInfo.Remark,
                    Address = tagInfo.Address,
                    OrderNo = tagInfo.OrderNo
                };
                if (tagInfo.IsEnableText == "已启用")
                {
                    UpdataData.IsEnable = true;
                }
                else if (tagInfo.IsEnableText == "已禁用")
                {
                    UpdataData.IsEnable = false;
                }
                string Sql = @"update TagInfo
                           set OrderNo = @OrderNo,
                               Remark = @Remark,
                               Address = @Address,
                               IsEnable = @IsEnable
                          where Id = @Id AND (
                            ISNULL(OrderNo,0) != @OrderNo
                            or ISNULL(Remark,'') != @Remark
                            or ISNULL(Address,'') != @Address
                            or IsEnable != @IsEnable
                          )";
                int result = DapperTools.Update<TagInfo>(Sql, UpdataData);
                string LogContentg = "";
                if (Befre.OrderNo != UpdataData.OrderNo)
                {
                    LogContentg += "排序序号【" + Befre.OrderNo + "】→【" + UpdataData.OrderNo + "】、";
                }
                if (Befre.Remark != UpdataData.Remark)
                {
                    LogContentg += "说明【" + Befre.Remark + "】→【" + UpdataData.Remark + "】、";
                }
                if (Befre.Address != UpdataData.Address)
                {
                    LogContentg += "地址【" + Befre.Address + "】→【" + UpdataData.Address + "】、";
                }
                if (Befre.IsEnable != UpdataData.IsEnable)
                {
                    LogContentg += "是否启用【" + Befre.IsEnableText + "】→【" + UpdataData.IsEnableText + "】、";
                }
                if (LogContentg != "")
                {
                    LogContentg = LogContentg.Substring(0, LogContentg.Length - 1) + "。";
                    LogTool.SaveLog("控制程序块信息配置", "标签【" + Befre.TagDesc + "】进行了如下修改：" + LogContentg);
                }
                if (result > 0)
                {
                    InitTagInfoList();
                }
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "保存控制程序块异常");
            }
        }

        /// <summary>
        /// 初始化标签列表
        /// </summary>
        private void InitTagInfoList()
        {
            string WhereStr = " where 1 = 1";
            if (EquipmentName != null && EquipmentName.Trim() != "" && EquipmentName.Trim() != "--请选择--")
            {
                WhereStr += " AND EquipmentName = '" + EquipmentName + "'";
            }
            if (TagDesc != null && TagDesc.Trim() != "")
            {
                if (XyhUtils.IsHasSQLInject(TagDesc))
                {
                    WindowManager.ShowWarning("警告", "含义不可使用包含SQL注入关键词的内容进行搜索操作！");
                    return;
                }
                WhereStr += " AND TagDesc LIKE '%" + TagDesc + "%'";
            }
            if (Address != null && Address.Trim() != "")
            {
                if (XyhUtils.IsHasSQLInject(Address))
                {
                    WindowManager.ShowWarning("警告", "地址不可使用包含SQL注入关键词的内容进行搜索操作！");
                    return;
                }
                WhereStr += " AND Address LIKE '%" + Address + "%'";
            }
            if (ValueType != null && ValueType.Trim() != "" && ValueType.Trim() != "--请选择--")
            {
                WhereStr += " AND ValueType = '" + ValueType + "'";
            }
            if (ReadOrWriteText != null && ReadOrWriteText.Trim() != "" && ReadOrWriteText.Trim() != "--请选择--")
            {
                if (ReadOrWriteText.Trim() == "可读")
                {
                    WhereStr += " AND ReadOrWrite = 1";
                }
                else if (ReadOrWriteText.Trim() == "可读可写")
                {
                    WhereStr += " AND ReadOrWrite = 0";
                }
            }
            if (IsEnableText != null && IsEnableText.Trim() != "" && IsEnableText.Trim() != "--请选择--")
            {
                if (IsEnableText.Trim() == "已启用")
                {
                    WhereStr += " AND IsEnable = 1";
                }
                else if (IsEnableText.Trim() == "已禁用")
                {
                    WhereStr += " AND IsEnable = 0";
                }
            }
            string Sql = "select * from TagInfo " + WhereStr + " order by EquipmentName,orderNo";
            TagInfoList = DapperTools.QueryOc<TagInfo>(Sql);
        }
    }
}
